package com.mt.mtyx.activity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mt.mtyx.activity.mapper.ActivityInfoMapper;
import com.mt.mtyx.activity.mapper.ActivityRuleMapper;
import com.mt.mtyx.activity.mapper.ActivitySkuMapper;
import com.mt.mtyx.activity.service.ActivityInfoService;
import com.mt.mtyx.common.utils.Helper;
import com.mt.mtyx.dto.activity.ActivityRuleDto;
import com.mt.mtyx.entity.activity.ActivityInfo;
import com.mt.mtyx.entity.activity.ActivityRule;
import com.mt.mtyx.entity.activity.ActivitySku;
import com.mt.mtyx.entity.product.SkuInfo;
import com.mt.mtyx.product.ProductFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 营销活动业务层
 *
 * @author WMT
 * @Date 2023/7/24 15:56
 */
@Service
public class ActivityInfoServiceImpl extends ServiceImpl<ActivityInfoMapper, ActivityInfo> implements ActivityInfoService {

    @Autowired
    private ActivityRuleMapper activityRuleMapper;

    @Autowired
    private ActivitySkuMapper activitySkuMapper;

    @Autowired
    private ProductFeignClient productFeignClient;


    @Override
    public IPage<ActivityInfo> selectAll(Page<ActivityInfo> activityInfoPage) {
        Page<ActivityInfo> page = baseMapper.selectPage(activityInfoPage, null);
        // 把枚举类型的活动类型转换成对应的字符串
        List<ActivityInfo> records = page.getRecords();
        if (!CollectionUtils.isEmpty(records)) {
            for (ActivityInfo record : records) {
                record.setActivityTypeString(record.getActivityType().getComment());
            }
        }
        return page;
    }

    @Override
    public boolean existsByName(String activityName) {
        return baseMapper.exists(
                new LambdaQueryWrapper<ActivityInfo>().eq(ActivityInfo::getActivityName, activityName)
        );
    }

    @Override
    public int insert(ActivityInfo activityInfo) {
        Helper.setBaseProperties(activityInfo, LocalDateTime.now());
        return baseMapper.insert(activityInfo);
    }

    @Override
    public int delete(Long id) {
        return baseMapper.deleteById(id);
    }

    @Override
    public int batchDelete(List<Long> ids) {
        return baseMapper.deleteBatchIds(ids);
    }

    @Override
    public int update(ActivityInfo activityInfo) {
        activityInfo.setUpdateTime(LocalDateTime.now());
        return baseMapper.updateById(activityInfo);
    }

    @Override
    public Map<String, Object> getActivityRuleListById(Long activityId) {
        Map<String, Object> map = new HashMap<>(2);
        // 1.根据活动id，查询活动规则列表
        LambdaQueryWrapper<ActivityRule> activityRuleWrapper = new LambdaQueryWrapper<>();
        activityRuleWrapper.eq(ActivityRule::getActivityId, activityId);
        map.put("activityRuleList", activityRuleMapper.selectList(activityRuleWrapper));

        // 2.根据活动id，查询使用规则的商品skuId列表，再远程调用根据skuId列表查询商品详情
        LambdaQueryWrapper<ActivitySku> activitySkuWrapper = new LambdaQueryWrapper<>();
        activitySkuWrapper.eq(ActivitySku::getActivityId, activityId);
        List<ActivitySku> activitySkus = activitySkuMapper.selectList(activitySkuWrapper);
        // 获取所有skuId
        if (!CollectionUtils.isEmpty(activitySkus)) {
            List<Long> skuIds = activitySkus.stream().map(ActivitySku::getSkuId).collect(Collectors.toList());
            List<SkuInfo> skuInfoList = productFeignClient.getSkuInfoListByIds(skuIds);
            map.put("skuInfoList", skuInfoList);
        }
        return map;
    }

    @Override
    @Transactional
    public int saveActivityRule(ActivityRuleDto dto) {
        int result = 0;
        LocalDateTime now = LocalDateTime.now();
        // 1.根据活动id删除之前的活动规则
        activityRuleMapper.delete(
                new LambdaQueryWrapper<ActivityRule>().eq(ActivityRule::getActivityId, dto.getActivityId())
        );
        activitySkuMapper.delete(
                new LambdaQueryWrapper<ActivitySku>().eq(ActivitySku::getActivityId, dto.getActivityId())
        );

        // 2.添加活动规则
        ActivityInfo activityInfoDb = baseMapper.selectById(dto.getActivityId());
        List<ActivityRule> activityRuleList = dto.getActivityRuleList();
        if (!CollectionUtils.isEmpty(activityRuleList)) {
            List<ActivityRule> activityRules = activityRuleList.stream()
                    .peek(data -> {
                        data.setActivityId(dto.getActivityId());
                        data.setActivityType(activityInfoDb.getActivityType());
                        Helper.setBaseProperties(data, now);
                    })
                    .collect(Collectors.toList());
            activityRuleMapper.batchSave(activityRules);
        }
        // 3.添加活动参与商品
        List<ActivitySku> activitySkuList = dto.getActivitySkuList();
        if (!CollectionUtils.isEmpty(activitySkuList)) {
            List<ActivitySku> activitySkus = activitySkuList.stream()
                    .peek(data -> {
                        data.setActivityId(dto.getActivityId());
                        Helper.setBaseProperties(data, now);
                    })
                    .collect(Collectors.toList());
            result = activitySkuMapper.batchSave(activitySkus);
        }
        return result;
    }

    @Override
    public List<SkuInfo> getSkuInfoByKeyword(String keyword) {
        // 1.根据关键词查询商品信息列表
        List<SkuInfo> skuInfoList = productFeignClient.getSkuInfoListByKeyword(keyword);

        // 1.1 获取所有的商品id
        if (CollectionUtils.isEmpty(skuInfoList)) {
            return Collections.emptyList();
        }
        List<Long> skuIds = skuInfoList.stream().map(SkuInfo::getId).collect(Collectors.toList());

        // 2.判断添加的商品是否已经存在其他活动
        List<Long> existIds = baseMapper.existBySkuInfoId(skuIds);
        // 2.1排除已存在活动且活动未结束的商品
        return skuInfoList.stream()
                .filter(data -> !existIds.contains(data.getId()))
                .collect(Collectors.toList());
    }
}
